package com.haozi.core;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.haozi.config.DataSourcelConfig;
import com.haozi.config.GlobalConfig;
import com.haozi.constants.ConfigConstant;
import com.haozi.dto.PointResult;
import com.haozi.event.GetPointAfterEvent;
import com.haozi.exception.SystemException;
import com.haozi.provider.GetDataProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zyh
 * @version 1.0
 * @date 2022/4/27 11:19 上午
 */
@Component
@Slf4j
public class DataMonitor {
    @Autowired
    List<GetDataProvider> getDataProviders;

    @Autowired
    ApplicationEventPublisher applicationEventPublisher;
    @Autowired
    DingDingDataHandler dingDingDataHandler;
    @Autowired
    GlobalConfig globalConfig;

    /**
     * 开始
     *
     * @param dataSourcelConfig
     */
    public void start(DataSourcelConfig dataSourcelConfig) {


        String mention = globalConfig.getProperties(ConfigConstant.START_MENTION);
        String refreshSecondStr = globalConfig.getProperties(ConfigConstant.REFRESH_SECOND);
        int refreshSeconds = 20;
        if(NumberUtil.isNumber(refreshSecondStr)){
            refreshSeconds = NumberUtil.parseInt(refreshSecondStr);
        }

        if (StrUtil.isNotBlank(mention)) {
            dingDingDataHandler.sendMesg("开盘提醒", mention);
        }
        Timer timer = new Timer();

        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {

                PointResult currentPoint = getCurrentPoint(dataSourcelConfig);

                if (!currentPoint.isSuccess()) {
                    throw new SystemException("获取实时数据失败");
                }
                //获取后发事件
                GetPointAfterEvent getPointAfterEvent = new GetPointAfterEvent(this, currentPoint);
                applicationEventPublisher.publishEvent(getPointAfterEvent);
            }
        }, 0, refreshSeconds * 1000);
    }

    /**
     * 获取当前点数
     *
     * @return
     */
    private PointResult getCurrentPoint(DataSourcelConfig globalConfig) {

        for (GetDataProvider getDataProvider : getDataProviders) {

            if (getDataProvider.support(globalConfig)) {
                return getDataProvider.getData(globalConfig);
            }
        }
        throw new SystemException("找不到对应处理类");
    }


}
